package cn.openea.perpartner.meily.rabbit.service.impl.payment;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.evaluation.web.entity.EvaluationTask;
import cn.openea.perpartner.evaluation.web.service.IEvaluationTaskService;
import cn.openea.perpartner.meily.rabbit.domain.PayDto;
import cn.openea.perpartner.meily.thirdparty.WxPaySystemApi;
import cn.openea.perpartner.meily.web.entity.GroupBuyingSub;
import cn.openea.perpartner.meily.web.entity.ProvideSamples;
import cn.openea.perpartner.meily.web.entity.ProvideSamplesSub;
import cn.openea.perpartner.meily.web.service.IGroupBuyingSubService;
import cn.openea.perpartner.meily.web.service.IProvideSamplesService;
import cn.openea.perpartner.meily.web.service.IProvideSamplesSubService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;

/**
 * @author rains
 * @since 2023-05-29 09:38
 */
@Slf4j
@Component
public class PayConsumerService {

    @Autowired
    private IProvideSamplesService provideSamplesService;
    @Autowired
    private IProvideSamplesSubService provideSamplesSubService;
    @Autowired
    private IGroupBuyingSubService groupBuyingSubService;
    @Autowired
    private IEvaluationTaskService evaluationTaskService;
    @Resource
    private WxPaySystemApi wxPaySystemApi;

    /**
     * 支付消费业务队列
     * 支付成功、0元支付
     * @param object
     * @param deliveryTag
     * @param channel
     * @throws IOException
     */
//    @RabbitListener(queues = "${wxpay.business.queue}")
    @RabbitListener(queuesToDeclare ={@Queue(name = "wxpay.business.queue",durable = "true",autoDelete = "false",exclusive = "false")})
    public void receiveBusiness(JSONObject object, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        try {
            /**
             * object.orderExtJson = {
             *      type: 0,
             *      data: businessData
             *  }
             * type说明:
             * 0：发起样品；
             * 1：领取样品；
             * 2：拼团购买；
             * 3：直接够买；
             * 4：发起测评
             */

            System.out.println("************************************");
            System.out.println("开始支付消息消费....");

            PayDto payDto = JSON.toJavaObject(object, PayDto.class);
            if(BeanUtil.isNotEmpty(payDto) && StrUtil.isNotBlank(payDto.getOrderExtJson())){

                // 订单的额外信息JSON
                JSONObject orderExtObj = JSONObject.parseObject(payDto.getOrderExtJson());
                System.out.println("************orderExtObj******************");
                System.out.println("orderExtObj=" + orderExtObj);

                String type = orderExtObj.getString("type");// 用于区分具体业务的类型
                JSONObject dataObj = orderExtObj.getJSONObject("data");// 业务数据

                System.out.println("************dataObj业务数据******************");
                System.out.println("dataObj=" + dataObj);

                // 发起样品活动的支付
                if("0".equals(type)){
                    ProvideSamples samples = JSON.toJavaObject(dataObj, ProvideSamples.class);
                    initiateSampleActivities(samples);
                    System.out.println("执行发起样品结束。");
                    System.out.println("********************************");

                    /*// 判断订单是否支付成功
                    JSONObject paramObj = new JSONObject();
                    paramObj.put("userid", samples.getInitiatorId());// 发起人id
                    paramObj.put("tradeNo", samples.getOrderId());// 订单id
                    JSONObject resObj = wxPaySystemApi.doQueryWxPayOk(paramObj);
                    if(ObjectUtil.isNotEmpty(resObj) && "200".equals(resObj.getString("code"))){
                        initiateSampleActivities(samples);
                        System.out.println("执行发起样品结束。");
                        System.out.println("********************************");
                    } else {
                        System.out.println("发起样品的订单未支付成功，不进行业务处理。");
                        System.out.println("********************************");
                    }*/
                }

                // 领取样品的支付
                if("1".equals(type)){
                    ProvideSamplesSub samplesSub = JSON.toJavaObject(dataObj, ProvideSamplesSub.class);
                    collectSamples(samplesSub);
                    System.out.println("执行领取样品结束。");
                    System.out.println("********************************");

                    /*// 判断是否支付成功
                    JSONObject paramObj = new JSONObject();
                    paramObj.put("userid", samplesSub.getPartnerId());// 消费者id
                    paramObj.put("tradeNo", samplesSub.getOrderId());// 订单id
                    JSONObject resObj = wxPaySystemApi.doQueryWxPayOk(paramObj);
                    if(ObjectUtil.isNotEmpty(resObj) && "200".equals(resObj.getString("code"))){
                        collectSamples(samplesSub);
                        System.out.println("执行领取样品结束。");
                        System.out.println("********************************");
                    } else {
                        System.out.println("领取样品的订单未支付成功，不进行业务处理。");
                        System.out.println("********************************");
                    }*/
                }

                // 参与拼团购买商品的支付
                if("2".equals(type)){
                    GroupBuyingSub groupBuyingSub = JSON.toJavaObject(dataObj, GroupBuyingSub.class);
                    groupPurchase(groupBuyingSub);
                    System.out.println("执行参与拼团购买商品结束。");
                    System.out.println("********************************");

                    /*// 判断是否支付成功
                    JSONObject paramObj = new JSONObject();
                    paramObj.put("userid", groupBuyingSub.getPartnerId());// 消费者id
                    paramObj.put("tradeNo", groupBuyingSub.getOrderId());// 订单id
                    JSONObject resObj = wxPaySystemApi.doQueryWxPayOk(paramObj);
                    if(ObjectUtil.isNotEmpty(resObj) && "200".equals(resObj.getString("code"))){
                        groupPurchase(groupBuyingSub);
                        System.out.println("执行参与拼团购买商品结束。");
                        System.out.println("********************************");
                    } else {
                        System.out.println("参与拼团购买商品的订单未支付成功，不进行业务处理。");
                        System.out.println("********************************");
                    }*/
                }

                // 直接购买商品的支付
                if("3".equals(type)){
                    GroupBuyingSub groupBuyingSub = JSON.toJavaObject(dataObj, GroupBuyingSub.class);
                    directPurchasing(groupBuyingSub);
                    System.out.println("执行直接购买商品结束。");
                    System.out.println("********************************");

                    /*// 判断是否支付成功
                    JSONObject paramObj = new JSONObject();
                    paramObj.put("userid", groupBuyingSub.getPartnerId());// 消费者id
                    paramObj.put("tradeNo", groupBuyingSub.getOrderId());// 订单id
                    JSONObject resObj = wxPaySystemApi.doQueryWxPayOk(paramObj);
                    if(ObjectUtil.isNotEmpty(resObj) && "200".equals(resObj.getString("code"))){
                        directPurchasing(groupBuyingSub);
                        System.out.println("执行直接购买商品结束。");
                        System.out.println("********************************");
                    } else {
                        System.out.println("直接购买商品的订单未支付成功，不进行业务处理。");
                        System.out.println("********************************");
                    }*/
                }

                // 发起测评
                if("4".equals(type)){
                    EvaluationTask evaluationTask = JSON.toJavaObject(dataObj, EvaluationTask.class);
                    initiateEvaluationActivities(evaluationTask);
                    System.out.println("执行发起测评结束。");
                    System.out.println("********************************");
                }

            }

            // 消息消费成功，手动确认消息,消息从队列中删除
            channel.basicAck(deliveryTag, false);

        } catch (Exception e) {
            log.error(e.getMessage());
            // 消息消费失败，手动拒绝消息,消息从队列中删除
            channel.basicNack(deliveryTag, false, false);
        }
    }

    /**
     * 发起样品活动
     * @param samples
     * @return
     */
    public void initiateSampleActivities(ProvideSamples samples){
        // 1.根据订单号先判断业务处理是否已完成
        if(StrUtil.isNotBlank(samples.getOrderId())){
            LambdaQueryWrapper<ProvideSamples> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProvideSamples::getOrderId, samples.getOrderId());
            ProvideSamples samples1 = provideSamplesService.getOne(wrapper);
            if(BeanUtil.isEmpty(samples1)){
                // 发布样品活动
                provideSamplesService.publish(samples);
            }
        }
    }

    /**
     * 领取样品
     * @param samplesSub
     * @return
     */
    public void collectSamples(ProvideSamplesSub samplesSub){
        // 1.根据订单号先判断业务处理是否已完成
        if(StrUtil.isNotBlank(samplesSub.getOrderId())){
            LambdaQueryWrapper<ProvideSamplesSub> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProvideSamplesSub::getOrderId, samplesSub.getOrderId());
            ProvideSamplesSub samplesSub1 = provideSamplesSubService.getOne(wrapper);
            if(BeanUtil.isEmpty(samplesSub1)){
                // 领取样品
                provideSamplesSubService.receiveProvideSamples(samplesSub);
            }
        }
    }

    /**
     * 参与拼团购买商品
     * @param groupBuyingSub
     * @return
     */
    public void groupPurchase(GroupBuyingSub groupBuyingSub) throws ParseException {
        // 1.根据订单号先判断业务处理是否已完成
        if(StrUtil.isNotBlank(groupBuyingSub.getOrderId())){
            LambdaQueryWrapper<GroupBuyingSub> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GroupBuyingSub::getOrderId, groupBuyingSub.getOrderId());
            GroupBuyingSub groupBuyingSub1 = groupBuyingSubService.getOne(wrapper);
            if(BeanUtil.isEmpty(groupBuyingSub1)){
                // 参与拼团购买商品
                groupBuyingSubService.join(groupBuyingSub);
            }
        }
    }

    /**
     * 直接购买商品
     * @param groupBuyingSub
     * @return
     */
    public void directPurchasing(GroupBuyingSub groupBuyingSub) throws ParseException {
        // 1.根据订单号先判断业务处理是否已完成
        if(StrUtil.isNotBlank(groupBuyingSub.getOrderId())){
            LambdaQueryWrapper<GroupBuyingSub> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GroupBuyingSub::getOrderId, groupBuyingSub.getOrderId());
            GroupBuyingSub groupBuyingSub1 = groupBuyingSubService.getOne(wrapper);
            if(BeanUtil.isEmpty(groupBuyingSub1)){
                // 直接购买商品
                groupBuyingSubService.directPurchase(groupBuyingSub);
            }
        }
    }

    /**
     * 发起测评活动
     * @param evaluationTask
     * @return
     */
    public void initiateEvaluationActivities(EvaluationTask evaluationTask){
        // 1.根据订单号先判断业务处理是否已完成
        if(StrUtil.isNotBlank(evaluationTask.getOrderId())){
            LambdaQueryWrapper<EvaluationTask> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EvaluationTask::getOrderId, evaluationTask.getOrderId());
            EvaluationTask evaluationTask1 = evaluationTaskService.getOne(wrapper);
            if(BeanUtil.isEmpty(evaluationTask1)){
                // 发起测评活动
                evaluationTaskService.publish(evaluationTask);
            }
        }
    }

}
